package data.nanjing.expo.services;

import org.sphx.api.SphinxClient;
import org.sphx.api.SphinxException;
import org.sphx.api.SphinxMatch;
import org.sphx.api.SphinxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class TextSearchService {

    @Value("${sphinx.host}")
    private String sphinxHost;

    @Value("${sphinx.port}")
    private int sphinxPort;

    private static SphinxClient client = null;

    private SphinxClient getClient() {
        System.out.println(client);
        if(client == null) {
            synchronized (TextSearchService.class) {
                if(client == null) {
                    client = new SphinxClient(this.sphinxHost, this.sphinxPort);
                }
            }
        }
        return client;
    }

    public List<SphinxMatch> search(String queryString, String index) {
        try {
            SphinxResult sphinxResult = this.getClient().Query(queryString, index);
            List<SphinxMatch> list = Arrays.asList(sphinxResult.matches);
            return list;
        } catch (SphinxException e) {
            return null;
        }
    }

}
